/**
 * 为了兼容旧数据，这边先判断如果存在  const { oldEmployeeCardInfo, newEmployeeCardInfo } = businessData;
 * 的情况下，去这两个字段，如果没有的话。走原来的逻辑比较复杂，还是得通过组织跟员工code去判断当前这个人
 */

import React, { useState, useMemo } from 'react';
import { Form, Input, Col, Popover } from 'antd';
import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';
import { useRequest, defaultFormatResult } from '@/hooks';

import { withRouter, router } from 'umi';
import { getPostApplyData } from '@/pages/WorkFlow/services';
import SupervisorProfile from '@/pages/Organization/EmployeeManage/components/SupervisorProfile';
import { guid } from '@/utils/utils';
import Employee from '@/pages/Organization/OrgFlow/components/employee';
import { getEmployeeList } from '@/pages/Organization/OrgFlow/services';

import styles from './index.less';

const LabelValue = ({ label, value, children }) => (
    <div className={styles.labelAndValueWrapper}>
        <Col span={4}>
            <div style={{ textAlign: 'right' }}>{label}：</div>
        </Col>
        <Col span={12}>
            {value ? (
                <span
                    // eslint-disable-next-line react/no-danger
                    dangerouslySetInnerHTML={{
                        __html: value && value.replace(/[\r\n]+/g, '<br />')
                    }}
                />
            ) : null}
            <div style={{ display: 'inline-block', minWidth: 120 }}>{children}</div>
        </Col>
    </div>
);

const modText = text => {
    if (text) {
        return `(${text})`;
    }
    return '';
};
const operationType = {
    0: '新增',
    1: '修改',
    2: '卸任'
};

/**
 * 设置主管套件流程
 */

const SupervisorSet = ({ dataSource, form, formValueMap = {}, location }) => {
    const { getFieldDecorator } = form;
    const { children: list = [] } = dataSource;
    const hiDataId = location?.query?.hiDataId || formValueMap?.hiDataId;
    const [businessData, setBusinessData] = useState([]);

    const [oldUserInfo, setOldUserInfo] = React.useState();
    const [newUserInfo, setNewUserInfo] = React.useState();
    const [leaveUserInfo, setLeaveUserInfo] = React.useState();

    useRequest(() => getPostApplyData(hiDataId), {
        refreshDeps: [hiDataId],
        ready: !!hiDataId,
        onSuccess: v => {
            const { code, data } = v;
            if (code === 10000) {
                setBusinessData(data);
            }
        }
    });
    // 获取员工
    const { data: EmployeeList } = useRequest(
        () =>
            getEmployeeList({
                dutyType: 0
            }),
        {
            ...defaultFormatResult
        }
    );

    /**
     * 这边很多判断做了兼容容错，吐血
     */
    const renderItem = useMemo(() => {
        const { oldEmployeeCardInfo, newEmployeeCardInfo } = businessData;
        // 卸任
        if (businessData?.operationType === 2) {
            return (
                <>
                    <LabelValue label="卸任机构">
                        {businessData?.oldBusinessData?.organizationName || '-'}
                        <a
                            style={{ marginLeft: 10 }}
                            onClick={() => {
                                history.push({
                                    pathname: '/office/personnelManagement/organization/departmentinfo',
                                    state: {
                                        tabRoute: true,
                                        tabRefresh: true
                                    },
                                    query: {
                                        organizationCode: businessData?.oldBusinessData?.organizationCode
                                    }
                                });
                            }}
                        >
                            详情
                        </a>
                    </LabelValue>
                    {businessData?.titleName ? (
                        <LabelValue label="主管岗位">
                            {businessData?.titleName}{' '}
                            <a
                                style={{ marginLeft: 10 }}
                                onClick={() => {
                                    history.push({
                                        pathname: '/office/personnelManagement/organization/postdetail',
                                        state: {
                                            tabRoute: true,
                                            tabRefresh: true
                                        },
                                        query: {
                                            dutyCode: businessData?.titleValue,
                                            organizationCode: businessData.organizationCode
                                        }
                                    });
                                }}
                            >
                                详情
                            </a>
                        </LabelValue>
                    ) : null}
                    <LabelValue label="卸任主管">
                        {oldEmployeeCardInfo ? (
                            <Popover
                                key={guid()}
                                getPopupContainer={node => node}
                                content={<Employee employeeInfo={oldEmployeeCardInfo} organizationType={3} />}
                                placement="bottomLeft"
                            >
                                {oldEmployeeCardInfo?.employeeName || '-'}
                                {oldEmployeeCardInfo
                                    ? modText(`${oldEmployeeCardInfo?.dutyAlias}/${oldEmployeeCardInfo?.rankValue}`)
                                    : null}
                            </Popover>
                        ) : (
                            <Popover
                                key={guid()}
                                getPopupContainer={node => node}
                                content={
                                    <Employee
                                        employeeCode={businessData?.oldBusinessData.employeeCode}
                                        organizationCode={businessData?.oldBusinessData.organizationCode}
                                        organizationType={3}
                                    />
                                }
                                placement="bottomLeft"
                            >
                                {leaveUserInfo?.employeeName || '-'}
                                {leaveUserInfo
                                    ? modText(`${leaveUserInfo?.dutyAlias}/${leaveUserInfo?.rankValue}`)
                                    : null}
                            </Popover>
                        )}
                    </LabelValue>
                    <LabelValue label="理由" value={businessData?.remark || '-'} />
                </>
            );
        }
        return (
            <>
                <LabelValue label="管理机构">
                    {businessData?.organizationName || '-'}
                    <a
                        style={{ marginLeft: 10 }}
                        onClick={() => {
                            history.push({
                                pathname: '/office/personnelManagement/organization/departmentinfo',
                                state: {
                                    tabRoute: true,
                                    tabRefresh: true
                                },
                                query: {
                                    organizationCode: businessData?.organizationCode
                                }
                            });
                        }}
                    >
                        详情
                    </a>
                </LabelValue>
                {businessData?.titleName ? (
                    <LabelValue label="主管岗位">
                        {businessData?.titleName}{' '}
                        <a
                            style={{ marginLeft: 10 }}
                            onClick={() => {
                                history.push({
                                    pathname: '/office/personnelManagement/organization/postdetail',
                                    state: {
                                        tabRoute: true,
                                        tabRefresh: true
                                    },
                                    query: {
                                        dutyCode: businessData?.titleValue,
                                        organizationCode: businessData.organizationCode
                                    }
                                });
                            }}
                        >
                            详情
                        </a>
                    </LabelValue>
                ) : null}
                {businessData?.oldBusinessData?.employeeName ? (
                    <LabelValue label="原主管">
                        {oldEmployeeCardInfo ? (
                            <Popover
                                key={guid()}
                                getPopupContainer={node => node}
                                content={<Employee employeeInfo={oldEmployeeCardInfo} organizationType={3} />}
                                placement="bottomLeft"
                            >
                                {oldEmployeeCardInfo ? (
                                    <div>
                                        {oldEmployeeCardInfo?.employeeName}
                                        {modText(`${oldEmployeeCardInfo?.dutyAlias}/${oldEmployeeCardInfo?.rankValue}`)}
                                    </div>
                                ) : null}
                            </Popover>
                        ) : (
                            <Popover
                                key={guid()}
                                getPopupContainer={node => node}
                                content={
                                    <Employee
                                        employeeCode={businessData?.oldBusinessData.employeeCode}
                                        organizationCode={businessData?.oldBusinessData.organizationCode}
                                        organizationType={3}
                                    />
                                }
                                placement="bottomLeft"
                            >
                                {oldUserInfo ? (
                                    <div>
                                        {oldUserInfo?.employeeName}
                                        {modText(`${oldUserInfo?.dutyAlias}/${oldUserInfo?.rankValue}`)}
                                    </div>
                                ) : null}
                            </Popover>
                        )}
                    </LabelValue>
                ) : null}
                <LabelValue label="主管">
                    {newEmployeeCardInfo ? (
                        <Popover
                            key={guid()}
                            getPopupContainer={node => node}
                            content={<Employee employeeInfo={newEmployeeCardInfo} organizationType={3} />}
                            placement="bottomLeft"
                        >
                            {newEmployeeCardInfo ? (
                                <div>
                                    {newEmployeeCardInfo?.employeeName || '-'}
                                    {modText(`${newEmployeeCardInfo?.dutyAlias}/${newEmployeeCardInfo?.rankValue}`)}
                                </div>
                            ) : null}
                        </Popover>
                    ) : (
                        <Popover
                            key={guid()}
                            getPopupContainer={node => node}
                            content={
                                <Employee
                                    employeeCode={newUserInfo?.employeeCode}
                                    organizationCode={newUserInfo?.organizationCode}
                                    organizationType={3}
                                />
                            }
                            placement="bottomLeft"
                        >
                            {newUserInfo ? (
                                <div>
                                    {newUserInfo?.employeeName || '-'}
                                    {modText(`${newUserInfo?.dutyAlias}/${newUserInfo?.rankValue}`)}
                                </div>
                            ) : null}
                        </Popover>
                    )}
                </LabelValue>
                <LabelValue label="理由" value={businessData?.remark || '-'} />
            </>
        );
    }, [businessData, leaveUserInfo, newUserInfo, oldUserInfo]);

    React.useEffect(() => {
        const { oldEmployeeCardInfo, newEmployeeCardInfo } = businessData;
        if (oldEmployeeCardInfo && newEmployeeCardInfo) {
            // 如果是卸任的情况写，需要对表单的摘要进行修改一下
            if (businessData?.operationType === 2) {
                form.setFieldsValue({
                    leaderName: `${oldEmployeeCardInfo?.employeeName || '-'}${
                        oldEmployeeCardInfo
                            ? modText(`${oldEmployeeCardInfo?.dutyAlias}/${oldEmployeeCardInfo?.rankValue}`)
                            : null
                    }`
                });
            }
        } else {
            // TODO
            // 这个olduser 跟leaveUser数据由于没有后端数据固化，所以这边会先匹配员工code跟组织code
            // 但是审批通过后，在审批详情里面查看，就找不到数据，所以这时候只匹配员工code，如果找到就显示出来一条
            const oldUser =
                (EmployeeList &&
                    EmployeeList.find(
                        e =>
                            e.employeeCode === businessData?.oldBusinessData?.employeeCode &&
                            e.organizationCode === businessData?.organizationCode
                    )) ||
                (EmployeeList &&
                    EmployeeList.find(e => e.employeeCode === businessData?.oldBusinessData?.employeeCode));
            const newUser = EmployeeList && EmployeeList.find(e => e.employeeCode === businessData?.employeeCode);
            const leaveUser =
                (EmployeeList &&
                    EmployeeList.find(
                        e =>
                            e.employeeCode === businessData?.employeeCode &&
                            e.organizationCode === businessData?.organizationCode
                    )) ||
                (EmployeeList && EmployeeList.find(e => e.employeeCode === businessData?.employeeCode));
            setOldUserInfo(oldUser); // 从所有员工里面找到这个人
            setNewUserInfo(newUser); // 新主管
            setLeaveUserInfo(leaveUser); // 卸任主管
            // 如果是卸任的情况写，需要对表单的摘要进行修改一下
            if (businessData?.operationType === 2) {
                form.setFieldsValue({
                    leaderName: `${leaveUser?.employeeName || '-'}${
                        leaveUser ? modText(`${leaveUser?.dutyAlias}/${leaveUser?.rankValue}`) : null
                    }`
                });
            }
        }
    }, [EmployeeList, businessData]);

    return (
        <div className={styles.newFunctionWrapper}>
            {Array.isArray(list) &&
                list.map(item => {
                    const { label, formId, rules, extra } = item;
                    let { initialValue } = item;

                    if (formId === 'leaderName') {
                        initialValue = businessData?.employeeName;
                    }
                    if (formId === 'organizationName') {
                        initialValue = businessData?.organizationName;
                    }
                    // if (formId === 'titleName') {
                    //     initialValue = businessData?.titleName;
                    // }
                    if (formId === 'operationType') {
                        initialValue = operationType[businessData?.operationType];
                    }
                    return (
                        <Form.Item
                            label={label}
                            key={formId}
                            extra={extra}
                            style={{ display: item?.inRenderDom === false ? 'none' : 'block' }}
                        >
                            {getFieldDecorator(formId, {
                                initialValue,
                                rules
                            })(<AutoRenderComponent form={form} config={item} />)}
                        </Form.Item>
                    );
                })}
            <div className={styles.title}>基础信息</div>
            <div>{renderItem}</div>

            <div className={styles.title}>
                {businessData?.oldBusinessData?.employeeName && businessData?.operationType !== 2
                    ? '新主管概况'
                    : '主管概况'}
            </div>
            <Form.Item wrapperCol={24}>
                <SupervisorProfile
                    label={false}
                    value={businessData?.summarize ? JSON.parse(businessData?.summarize) : null}
                />
            </Form.Item>
            <Form.Item style={{ display: 'none' }}>
                {getFieldDecorator('hiDataId', {
                    initialValue: hiDataId
                })(<Input />)}
            </Form.Item>
        </div>
    );
};
export default withRouter(SupervisorSet);
